# 字典的常用方法

dict1 = {}
# 创建一个新字典，以前者(序列)中元素做字典的键，后者为字典所有键对应的初始值
dict1 = dict1.fromkeys((1, 3.14, 'hello'))
print(dict1)  # {1: None, 3.14: None, 'hello': None}

dict1 = dict1.fromkeys((1, 3.14, 'hello'), 'python')
print(dict1)  # {1: 'python', 3.14: 'python', 'hello': 'python'}

print(dict1.keys(), dict1.values(), dict1.items())
# dict_keys([1, 3.14, 'hello']) dict_values(['python', 'python', 'python']) dict_items([(1, 'python'), (3.14, 'python'), ('hello', 'python')])

# 当查找不存在的key值时，会报错
# print(dict1[2])
# 使用get ，当key值不存在，返回赋给它的值,未赋值时，返回None
print(dict1.get(2))  # None
print(dict1.get(2, 'two'))  # two

# 使用clear()清空字典，不建议直接赋值 空字典 即 {}
dict2 = dict1
print(dict2)  # {1: 'python', 3.14: 'python', 'hello': 'python'}
dict1 = {}
print(dict1)  # {},dict1被设为空字典
print(dict2)  # {1: 'python', 3.14: 'python', 'hello': 'python'}，但dict2还是原来的字典

# 当使用clear()后，都会清空
dict1 = {1: 110}
dict2 = dict1
dict1.clear()
print(dict1)  # {}
print(dict2)  # {}

# copy()，浅拷贝
dict1 = {1: 110, 3.14: 3.145927, 'hello': 'Hello,Python'}
dict2 = dict1.copy()
dict1[2] = 120
print(dict1)  # {1: 110, 3.14: 3.145927, 'hello': 'Hello,Python', 2: 120}
print(dict2)  # {1: 110, 3.14: 3.145927, 'hello': 'Hello,Python'}

# pop()删除字典给定键 key 所对应的值，返回值为被删除的值
print(dict1.pop(3.14))  # 3.145927
print(dict1)  # {1: 110, 'hello': 'Hello,Python', 2: 120}

# popitem()随机返回并删除字典中的一对键和值
# print(dict1.popitem())

# setdefault()和get()类似, 但如果键不存在于字典中，将会添加键并将值设为default
print(dict1.setdefault('hhh'))  # None
print(dict1)  # {1: 110, 'hello': 'Hello,Python', 2: 120, 'hhh': None}
dict1.setdefault(111, 'oneoneone')
print(dict1)  # {1: 110, 'hello': 'Hello,Python', 2: 120, 'hhh': None, 111: 'oneoneone'}

# dict.update(dict2) 把字典dict2的键/值对更新到dict里
dict3 = {1: 'one'}
dict1.update(dict3)
print(dict1)  # {1: 'one', 'hello': 'Hello,Python', 2: 120, 'hhh': None, 111: 'oneoneone'}
